namespace DotNetNuke.HttpModules
{
    
    using System;
    using System.Web;

    public class RewriterUtils
    {
        internal static string ResolveUrl(string appPath, string url)
        {
            if (url.Length == 0)
            {
                return url;
            }
            if (!url.StartsWith("~"))
            {
                return url;
            }
            if (url.Length == 1)
            {
                return appPath;
            }
            if ((Convert.ToString(url.ToCharArray()[1]) == "/") | (Convert.ToString(url.ToCharArray()[1]) == @"\"))
            {
                if (appPath.Length > 1)
                {
                    return (appPath + "/" + url.Substring(2));
                }
                return ("/" + url.Substring(2));
            }
            if (appPath.Length > 1)
            {
                return (appPath + "/" + url.Substring(1));
            }
            return (appPath + url.Substring(1));
        }

        internal static void RewriteUrl(HttpContext context, string sendToUrl)
        {
            string x = "";
            string y = "";
            RewriteUrl(context, sendToUrl, ref x, ref y);
        }

        internal static void RewriteUrl(HttpContext context, string sendToUrl, ref string sendToUrlLessQString, ref string filePath)
        {
            if (context.Request.QueryString.Count > 0)
            {
                if (sendToUrl.IndexOf("?") != -1)
                {
                    sendToUrl = sendToUrl + "&" + context.Request.QueryString.ToString();
                }
                else
                {
                    sendToUrl = sendToUrl + "?" + context.Request.QueryString.ToString();
                }
            }
            string queryString = string.Empty;
            sendToUrlLessQString = sendToUrl;
            if (sendToUrl.IndexOf("?") > 0)
            {
                sendToUrlLessQString = sendToUrl.Substring(0, sendToUrl.IndexOf("?"));
                queryString = sendToUrl.Substring(sendToUrl.IndexOf("?") + 1);
            }
            filePath = string.Empty;
            filePath = context.Server.MapPath(sendToUrlLessQString);
            context.RewritePath(sendToUrlLessQString, string.Empty, queryString);
        }
    }
}

